﻿using System;
using System.Windows.Forms;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
using System.Threading.Tasks;
using System.IO;

namespace WinForms_GettingStarted
{
    public partial class Form1 : Form
    {
        private string userDataFolder;
        private CoreWebView2Environment currentEnvironment;

        public Form1()
        {
            InitializeComponent();
            userDataFolder = CreateUniqueUserDataFolder();
            this.Load += Form1_Load;
        }

        private string CreateUniqueUserDataFolder()
        {
            // 创建一个基于时间戳的唯一文件夹
            string basePath = Path.Combine(Path.GetTempPath(), "WebView2Proxy");
            string uniquePath = Path.Combine(basePath, DateTime.Now.Ticks.ToString());
            
            try
            {
                if (!Directory.Exists(basePath))
                {
                    Directory.CreateDirectory(basePath);
                }
                
                if (!Directory.Exists(uniquePath))
                {
                    Directory.CreateDirectory(uniquePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建用户数据文件夹失败: " + ex.Message);
            }
            
            return uniquePath;
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            await InitializeWebView2();
        }

        private async Task InitializeWebView2(string proxyServer = null)
        {
            try 
            {
                // 如果已经初始化过，先完全销毁旧实例
                if (webView21 != null && webView21.CoreWebView2 != null)
                {
                    // 移除事件处理程序
                    webView21.CoreWebView2.NewWindowRequested -= CoreWebView2_NewWindowRequested;
                    webView21.NavigationStarting -= EnsureHttps;
                    
                    // 从控件集合中移除
                    tableLayoutPanel1.Controls.Remove(webView21);
                    
                    // 释放资源
                    webView21.Dispose();
                    webView21 = null;
                    
                    // 为GC创建条件
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    
                    // 为新的WebView2使用新的文件夹
                    userDataFolder = CreateUniqueUserDataFolder();
                    
                    // 创建新的WebView2控件
                    webView21 = new Microsoft.Web.WebView2.WinForms.WebView2
                    {
                        Dock = DockStyle.Fill,
                        Location = new System.Drawing.Point(4, 54),
                        Size = new System.Drawing.Size(1478, 1003),
                        TabIndex = 1
                    };
                    
                    // 添加到表单
                    tableLayoutPanel1.Controls.Add(webView21, 0, 1);
                }

                // 创建环境选项
                var options = new CoreWebView2EnvironmentOptions();
                if (!string.IsNullOrEmpty(proxyServer))
                {
                    options.AdditionalBrowserArguments = $"--proxy-server={proxyServer}";
                }

                // 创建新环境
                currentEnvironment = await CoreWebView2Environment.CreateAsync(null, userDataFolder, options);
                
                // 初始化WebView2
                await webView21.EnsureCoreWebView2Async(currentEnvironment);

                // 设置事件
                webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
                webView21.NavigationStarting += EnsureHttps;

                // 导航到初始页面
                if (string.IsNullOrEmpty(proxyServer))
                {
                    webView21.CoreWebView2.Navigate("https://www.baidu.com");
                }
                else
                {
                    webView21.CoreWebView2.Navigate("https://ip138.com/");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化出错: " + ex.Message);
            }
        }

        void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
        {
            String uri = args.Uri;
            textBox1.Text = uri;
        }

        private void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            e.Handled = true;
            if (webView21.CoreWebView2 != null)
            {
                webView21.CoreWebView2.Navigate(e.Uri);
            }
        }

        private void button_Click(object sender, EventArgs e)
        {
            if (webView21.CoreWebView2 == null) return;

            Button btn = (Button)sender;
            if (btn == button_go)
            {
                String url = textBox1.Text;
                if (url.StartsWith("http://") || url.StartsWith("https://"))
                {
                    webView21.CoreWebView2.Navigate(url);
                }
                else
                {
                    MessageBox.Show("请输入正确的URL");
                }
            }
            if (btn == button_back)
            {
                webView21.CoreWebView2.GoBack();
            }
            if (btn == button_reload)
            {
                webView21.CoreWebView2.Reload();
            }
        }

        private async void button_setproxy_Click(object sender, EventArgs e)
        {
            try
            {
                string proxyServer = textBox_proxy.Text.Trim();
                if (string.IsNullOrEmpty(proxyServer))
                {
                    MessageBox.Show("请输入代理服务器地址");
                    return;
                }

                // 使用新的代理设置重新初始化WebView2
                await InitializeWebView2(proxyServer);
                MessageBox.Show("代理设置成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置代理时出错: " + ex.Message);
            }
        }

        private async void button_clearproxy_Click(object sender, EventArgs e)
        {
            try
            {
                // 重新初始化WebView2（不设置代理）
                await InitializeWebView2();
                textBox_proxy.Clear();
                MessageBox.Show("代理设置已清除！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("清除代理时出错: " + ex.Message);
            }
        }

        private async void button_cookie(object sender, EventArgs e)
        {
            if (webView21.CoreWebView2 == null) return;

            var cookieManager = webView21.CoreWebView2.CookieManager;
            var cookiesCollection = await cookieManager.GetCookiesAsync(null);
            string cookies = "";
            foreach (var cookie in cookiesCollection)
            {
                cookies += cookie.Name + "=" + cookie.Value + ";";
            }
            
            try
            {
                this.Invoke((Action)delegate
                {
                    Clipboard.SetText(cookies);
                    MessageBox.Show("cookies文本已成功置入剪贴板。");
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("置入剪贴板时出错: " + ex.Message);
            }
        }

        private async void button_clearcache(object sender, EventArgs e)
        {
            try
            {
                if (webView21.CoreWebView2 != null)
                {
                    await webView21.CoreWebView2.Profile.ClearBrowsingDataAsync(
                        CoreWebView2BrowsingDataKinds.Cookies | 
                        CoreWebView2BrowsingDataKinds.CacheStorage | 
                        CoreWebView2BrowsingDataKinds.DiskCache
                    );
                    MessageBox.Show("缓存清理完成。");
                }
                else
                {
                    MessageBox.Show("WebView2尚未初始化完成。");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("清理缓存时出错: " + ex.Message);
            }
        }
    }
}
